package com.zboin.service;

import com.zboin.common.domain.AjaxResult;
import com.zboin.common.exception.BusinessException;
import com.zboin.framework.config.alioss.AliOssClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Slf4j
@Service
public class FileManageService {

    private static final String FILE_TYPE = "blog";
    private static final String IMAGE_TYPE = "image";

    @Value("${server.servlet.application-display-name}")
    private String displayName;

    private final AliOssClient aliOssClient;

    public FileManageService(AliOssClient aliOssClient) {
        this.aliOssClient = aliOssClient;
    }

    public AjaxResult uploadFile(MultipartFile file, String type) {
        String fileUrl;
        try {
            String fileName = generateFilePath(file.getOriginalFilename(), type);
            if (aliOssClient.fileExists(fileName)) {
                return AjaxResult.error("已存在同名文件");
            }
            fileUrl = aliOssClient.uploadFile(fileName, file.getInputStream());
            return AjaxResult.success("操作成功", fileUrl);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return AjaxResult.error();
    }

    private String generateFilePath(String filename, String type) {
        String date = DateUtils.formatDate(new Date(), "yyyy/MM");
        if (FILE_TYPE.equals(type)) {
            return displayName + "/" + FILE_TYPE + "/" + date + "/" + filename;
        } else if (IMAGE_TYPE.equals(type)) {
            return displayName + "/" + IMAGE_TYPE + "/" + date + "/" + filename;
        } else {
            throw new BusinessException(1001, "unsupport file type");
        }
    }

    public AjaxResult deleteFile(String filename) {
        aliOssClient.deleteFile(filename);
        return AjaxResult.success();
    }

    public byte[] getFileBytes(String url) {
        return aliOssClient.getObjectBytes(url);
    }
}
